<template>
  <div class='login_container'>
    <div class="login_box">
      <el-form ref="loginFormRef" :rules="loginRules" :model="loginForm"  status-icon class="login_form" label-width="80px">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item style="text-align: left">
          <el-checkbox v-model="isRemember">
          记住密码
          </el-checkbox>
          <!-- 找回密码 -->
        <el-button type="text" @click="open()" class="forgetPw" style="margin-left:150px">忘记密码？</el-button>
        </el-form-item>

        <el-form-item class="btns">
          <!-- <el-button type="button" @click="userLogin()">登录</el-button> -->
          <el-button @click="giteeLogin">gitee登录</el-button>
          <el-button type="primary" @click="submitForm()">登录</el-button>
          <el-button @click="resetForm('loginFormRef')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>

</template>

<script>
import { doLogin ,giteeLogin } from '@/api/login'
  export default {
    name: "Login",
    data() {
      return {
        url:'https://gitee.com/oauth/authorize?client_id=4878a2809400a5701e952d2b5e6327b4f10c3eca0f73352e8aa3f11b6c7a5fae&redirect_uri=http://localhost:9090/user/oauth2&response_type=code',
        loginForm:{
          username:'',
          password:''
        },
          loginRules: {
              username: [{ required: true, message:'请输入用户名',trigger: 'blur' },{min:3,max:10,message:'长度在3-10个字符',trigger:'blur'}],
              password: [{ required: true, message:'请输入密码', trigger: 'blur'},{min:5,max:12,message:'长度在5-12个字符',trigger:'blur'}]
          },
          isRemember: false//默认不记住密码
      }
    },
    mounted(){
      this.getCookie();  //首先判断cookie中的值
    },
    methods: {
      
      // 进入登录页面首先查看cookie中是否存储用户名、密码
      getCookie(){
        if(document.cookie.length>0){
          var arr = document.cookie.split(";"); 
          for(var i = 0;i<arr.length; i++){
            var userKey = arr[i].split("=");
            if(userKey[0].trim() == "username"){
               this.loginForm.username = userKey[1];
            }else if(userKey[0].trim() == "password"){
               this.loginForm.password = userKey[1];
            }else if(userKey[0].trim() == "isRemember"){
               this.isRemember = Boolean(userKey[1]); 
            }
          }
        }
      },
      //存储
      setCookie(username,password,days){
        var curDate = new Date();
            curDate.setTime(curDate.getTime() + 24*60*60*1000*days);  //设置cookie存储的有效时间
            window.document.cookie = "username" + "=" + username + ";path=/;expires=" + curDate.toGMTString();
            window.document.cookie = "password" + "=" + password + ";path=/;expires=" + curDate.toGMTString();
            window.document.cookie = "isRemember" + "=" + this.isRemember + ";path=/;expires=" + curDate.toGMTString();
      },
      //如果用户不选择记住密码清除cookie
      clearCookie(){
        this.setCookie("","",-1);
      },
      submitForm() {
      //登录时判断是否选择记住密码，如果是则设置cookie,不是清除cookie，然后再调用登录函数进行登录
       if(this.isRemember == true){
          this.setCookie(this.loginForm.username,this.loginForm.password,7)
        }else{
           this.clearCookie();
        }
        this.userLogin();  //调用登录函数
      },
      giteeLogin(){
        window.location.href='https://gitee.com/oauth/authorize?client_id=4878a2809400a5701e952d2b5e6327b4f10c3eca0f73352e8aa3f11b6c7a5fae&redirect_uri=http://localhost:9090/user/oauth2&response_type=code'
          // giteeLogin()
          // .then(response =>{
          //     console.log(response);
          //     if(response.data&&response.data.code==200){
          //       const token = response.data.data.token
          //       console.log(token);
          //       this.$message.success('登陆成功')
          //        // 存储token到浏览器
          //       localStorage.setItem('eleToken', token)
          //       // sessionStorage.setItem('token',res.token)
          //       this.$router.push({path:'/ucenter2'}); //用户名:hxy2 密码：123456  xiaoyan 密码：654321
          //       this.$store.commit('handleUserName', response.data.data);
          //     }
          // })
          // .catch(error=>{})
      },
      //登陆函数
      userLogin() {
        this.$refs.loginFormRef.validate( async valid => {
          if (!valid) return;
          // Cookies.set('name',this.loginForm.username)
          // await this.$http.post("http://localhost:9090/user/login","username="+this.loginForm.username+"&password="+this.loginForm.password)
          await doLogin(this.loginForm.username, this.loginForm.password)
            .then(response =>{
              // this.List2 = response.data.data 
              console.log(response)
              if(response.data&&response.data.code==200){
                // alert("操作成功！")
              
                const token = response.data.data.token
                console.log(token);
                this.$message.success('登陆成功')
                 // 存储token到浏览器
                localStorage.setItem('eleToken', token)
                // sessionStorage.setItem('token',res.token)
                this.$router.push({path:'/ucenter2'}); //用户名:hxy2 密码：123456  xiaoyan 密码：654321
                this.$store.commit('handleUserName', response.data.data);
                // this.$store.dispatch('saveUserInfo',response.data.data);//请求回来后，把用户信息存储到VUEX里
              }else{
                this.$message.success(response.data.data)
              }
            }) 
            .catch(error =>{});
        })
      },      
      resetForm(loginFormRef) {
          this.$refs[loginFormRef].resetFields();
      }
  }
 }
</script>

<style scoped>
  /* .login_container{
    background-color: #2b4b6b;
    height: 100%;
  } */
  body{
  background-color: #2b4b6b;
  /* background-color: #fff; */
  }
  .login_box{
    width: 450px;
    height: 300px;
    background-color: rgb(230, 219, 219);
    border-radius: 10px;
    position: relative;
    left:50%;
    top:50%;
    /* 居中对齐 */
    transform: translate(-50%,-50%); 
    margin-top:200px;
    /* background-color: skyblue; */
  }
  .btns {
     /* //弹性布局 */
    display: flex;
    /* // 尾部对齐 */
    justify-content: flex-end; 
  }
  .login_form {
    position: absolute;
    top:50%;
    left:50%;
    /* 居中对齐 */
    transform: translate(-50%,-50%);
    width: 100%;
    padding: 0 10px;
    background-color: rgb(230, 219, 219);

    /* // 设置边框 */
    box-sizing: border-box;
  }

</style>